<!doctype html>
<html>

<head>
	<meta charset="utf-8">
	<meta name="viewport" content="width=device-width, initial-scale=1">
	<title>Test</title>
	<script type="text/javascript">
		var audioCtx = new (window.AudioContext || window.webkitAudioContext)();


		// Stereo
		var channels = 1;

		var sounds = {};

		function load(soundName) {
			var req = new XMLHttpRequest();
			// req.open('GET', soundName + ".raw", true);
			req.open('GET', "https://qycdn.zhuoyoutech.com/qyresource/file/2020/2/19/C7Remioqc6rCHce/ddda38be-0430-4a87-ae80-28f2f0c91c04.pcm?16", true);

			req.overrideMimeType('text\/plain; charset=x-user-defined');
			req.onreadystatechange = function (aEvt) {
				if (req.readyState == 4) {
					if (req.status == 200) {
						sounds[soundName] = req.responseText;
						document.getElementById('play-' + soundName).style.display = 'block';
					} else {
						alert('failed loading audio');
					}
				}
			};
			req.send(null);
		}

		function play(soundName) {
			// Create an empty two second stereo buffer at the
			// sample rate of the AudioContext
			var frameCount = sounds[soundName].length / 2;

			var myAudioBuffer = audioCtx.createBuffer(channels, frameCount, 16000);
			for (var channel = 0; channel < channels; channel++) {

				var nowBuffering = myAudioBuffer.getChannelData(channel, 16, 16000);
				for (var i = 0; i < frameCount; i++) {
					// audio needs to be in [-1.0; 1.0]
					// for this reason I also tried to divide it by 32767
					// as my pcm sample is in 16-Bit. It plays still the
					// same creepy sound less noisy.
					var word = (sounds[soundName].charCodeAt(i * 2) & 0xff) + ((sounds[soundName].charCodeAt(i * 2 + 1) & 0xff) << 8);
					nowBuffering[i] = ((word + 32768) % 65536 - 32768) / 32768.0;
				}
			}
			// Get an AudioBufferSourceNode.
			// This is the AudioNode to use when we want to play an AudioBuffer
			var source = audioCtx.createBufferSource();
			// set the buffer in the AudioBufferSourceNode
			source.buffer = myAudioBuffer;
			// connect the AudioBufferSourceNode to the
			// destination so we can hear the sound
			source.connect(audioCtx.destination);
			// start the source playing
			source.start();
			setTimeout(() => {
				source.stop();
			}, 2000);
		}
		function init() {
			load("AminorPipe")
			load("sinewave")
			load("example")
		}
	</script>
</head>

<body onload="init();">
	<div>
		<button id="play-sinewave" type="button" onclick="play('sinewave')">Play sound 'sinewave'</button>
	</div>
	<div>
		<button id="play-AminorPipe" type="button" onclick="play('AminorPipe')">Play sound 'A minor pipe'</button>
	</div>
	<div>
		<button id="play-example" type="button" onclick="play('example')">Play sound 'example'</button>
	</div>
</body>

</html>